package com.example.hello.hello.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

public class JsonUtil {

	// 返回 实体类
	public static <T> T getBean(String jsonString, Class<T> cls) {
		T t = null;
		try {
			Gson gson = new Gson();
			t = gson.fromJson(jsonString, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	// 返回 实体类
	public static <T> T getBean(String jsonString, Class<T> cls,Class<T> clss) {
		T t = null;
		Gson gson;
		try {
			gson = new Gson();
			t = gson.fromJson(jsonString, cls);
		} catch (Exception e) {
			gson = new Gson();
			t = gson.fromJson(jsonString, clss);
		}
		return t;
	}

	public static <T> List<T> getBeans(String jsonString, ArrayList<T> clsT) {
		List<T> list = new ArrayList<T>();
		try {
			Gson gson = new Gson();
			Type type = new TypeToken<ArrayList<T>>() {
			}.getType();
			list = gson.fromJson(jsonString, type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public static <T> ArrayList<T> jsonToList(String json, Class<T> classOfT) {
		  Type type = new TypeToken<ArrayList<JsonObject>>(){}.getType();
		  ArrayList<JsonObject> jsonObjs = new Gson().fromJson(json, type);
		  
		  System.out.println(jsonObjs);
		  
		  ArrayList<T> listOfT = new ArrayList<>();
		  for (JsonObject jsonObj : jsonObjs) {
		      listOfT.add(new Gson().fromJson(jsonObj, classOfT));
		  }
		  
		  return listOfT;
	}

	public static List<Map<String, Object>> listKeyMaps(String jsonString) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString,
					new TypeToken<List<Map<String, Object>>>() {
					}.getType());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public static Map<String, Object> getMaps(String jsonString) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Gson gson = new Gson();
			map = gson.fromJson(jsonString,
					new TypeToken<Map<String, Object>>() {
					}.getType());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public static String createJsonString(Object value) {
		Gson gson = new Gson();
		String str = gson.toJson(value);
		return str;
	}

}
